package org.example.demo.atomic;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

@Slf4j
public class AtomicExample5 {
    // 用来原子的修改某个对象的某个字段，但该字段必须是volatile声明的以及必须是非static
    public static AtomicIntegerFieldUpdater<AtomicExample5> updater = AtomicIntegerFieldUpdater.newUpdater(AtomicExample5.class,"count");

    @Getter
    private volatile int count = 100;

    public static void main(String[] args) {
        AtomicExample5 atomicExample5 = new AtomicExample5();
        if(updater.compareAndSet(atomicExample5,100,120)){
            log.info("update success  1,count={}",atomicExample5.getCount());
        }

        if(updater.compareAndSet(atomicExample5,100,120)){
            log.info("update success  2,count={}",atomicExample5.getCount());
        }else {
            log.info("update failed,count={}",atomicExample5.getCount());
        }
    }
}
